package com.huonan.jb.tools.esuse.export.type;


import cn.hutool.core.io.FileUtil;
import cn.hutool.setting.dialect.Props;
import com.huonan.jb.tools.esuse.dto.EsHitsInfo;
import com.huonan.jb.tools.esuse.export.content.ExtractFields;
import com.huonan.jb.tools.esuse.export.enums.FileType;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.StringJoiner;

@Slf4j
public abstract class ExportFile {

     private volatile static boolean hasTitle;
     private volatile static boolean firstLine = true;

//     public void exportToFile(String content, String filePath) {
//          ExtractFields extractFields = new ExtractFields();
//          List<String> sourceFields = extractFields.sourceFields();
//          if (firstLine && hasTitle) {
//               if (firstLine) {
//                    firstLine = false;
//                    StringJoiner stringBuffer = new StringJoiner(",");
//                    sourceFields.forEach(stringBuffer::add);
//                    FileUtil.appendUtf8String(stringBuffer + FileUtil.getLineSeparator(), filePath);
//               }
//          }
//          log.info("导出文件: {}", filePath);
//          FileUtil.appendUtf8String(FileUtil.getLineSeparator() + content, filePath);
//     }

     public void exportToFile(List<String> content, String filePath) {
          ExtractFields extractFields = new ExtractFields();
          List<String> sourceFields = extractFields.sourceFields();
          if (firstLine && hasTitle) {
               if (firstLine) {
                    firstLine = false;
                    StringJoiner stringBuffer = new StringJoiner(",");
                    sourceFields.forEach(stringBuffer::add);
                    FileUtil.appendUtf8String(stringBuffer.toString(), filePath);
               }
          }
          log.info("导出文件: {}", filePath);
          FileUtil.appendUtf8Lines(content, filePath);
     }

     public static void exportHandle(Props props, EsHitsInfo dataResult,
                                     FileType fileType) {
          ExportFile exportFile;
          switch (fileType) {
               case JSON:
                    hasTitle = false;
                    exportFile = new ExportTextFile();
                    exportFile.exportDataToFile(props, dataResult);
                    break;
               case CSV:
                    hasTitle = true;
                    exportFile = new ExportCsvFile();
                    exportFile.exportDataToFile(props, dataResult);
                    break;
               default:
                    break;
          }
     }

     public abstract void exportDataToFile(Props props, EsHitsInfo dataResult);
}
